const dbm = require('../config/dbModels');
const db = require('../config/dbIns');
const { aseDecode}=require('../core/crypto')
const { createJWT } = require('../core/jwt')
const { createCookie } = require('../core/do-cookie');
const dbModels = require('../config/dbModels');


class LoginDao {
    /**
     * 创建用户
     * @param ctx 浏览器发送的数据
     * @return jwtStr
     */
    static async identifyUser(ctx) {
      let data = ctx.request.body
     
      //let dbRes = await dbm.User.findOne({ where: { username: data.username }, raw: true })
      let [err, dbRes] = await db.selectOne(['*'], 'users', { username: data.username })
      console.log('======呼啦啦',err,dbRes);
      if(err){
        throw new global.errs.ParameterException('用户名或密码错误.')
        //其实是用户名不存在,为防止被用户猜出真实意图,故写用户名或密码错误
      }
      if (!dbRes) { 
        //输入了一个不存在的用户名
        throw new global.errs.ParameterException('用户名真的不存在')
      }

        let plainPswd = aseDecode(dbRes.password)
      if(plainPswd!=data.password){
        throw new global.errs.ParameterException('用户名或密码错误')
        //其实是密码错误,为防止被用户猜出真实意图,故写用户名或密码错误
      }
      return dbRes



        // let psd = aseEncode(data.password)
        // var arr_res = await dbm.User.findOrCreate({ where: { username: data.username }, defaults: { password: psd} })
        // if (!arr_res[1]) {
        //     throw new global.errs.ParameterException('该用户名已存在')
        // }
        // let encode_id = aseEncode(arr_res[0].id+'')
        // let jwtStr = createJWT({ 'id': encode_id })
        // return jwtStr
    }
}
module.exports = LoginDao
